package com.getpebble.android.framework.protocol.outbound;

import com.getpebble.android.framework.protocol.EndpointId;
import com.getpebble.android.framework.util.ByteUtils;

public class PblOutboundRegistryMessage extends PblOutboundMessage {
    private final byte[] mByteValue;
    private final RegistryCommand mCommand;
    private final RegistryKey mKey;
    private final RegistryType mType;

    public enum RegistryCommand {
        READ(0),
        WRITE(2),
        REMOVE(4);
        
        private final int id;

        private RegistryCommand(int id) {
            this.id = id;
        }

        public int getId() {
            return this.id;
        }
    }

    public enum RegistryKey {
        PCB_TEST_DATE("mfg_pcbtestdate"),
        RTC_FREQ("mfg_rtcfreq"),
        TEST_RESULT("mfg_testresult"),
        MISC("mfg_misc"),
        FUNC_TEST("mfg_functest"),
        COLOR("mfg_color"),
        FAC_MODE("mfg_facmode");
        
        private final String mKeyCode;

        public String getString() {
            return this.mKeyCode;
        }

        private RegistryKey(String keyCode) {
            this.mKeyCode = keyCode;
        }
    }

    public enum RegistryType {
        SYSTEM(EndpointId.SYS_REG),
        FACTORY(EndpointId.FCT_REG);
        
        private final EndpointId mEndpointId;

        private RegistryType(EndpointId endpointId) {
            this.mEndpointId = endpointId;
        }

        public EndpointId getEndpointId() {
            return this.mEndpointId;
        }
    }

    public PblOutboundRegistryMessage(RegistryKey key, int value, RegistryType type, RegistryCommand cmd) {
        super(type.getEndpointId());
        this.mKey = key;
        this.mByteValue = ByteUtils.int2bytes(value);
        this.mType = type;
        this.mCommand = cmd;
    }

    public synchronized byte[] getBytes() {
        if (!areBytesCached()) {
            addBytes(Byte.valueOf((byte) this.mCommand.getId()));
            addBytes(Byte.valueOf((byte) (this.mKey.getString().length() & 255)));
            if (this.mCommand == RegistryCommand.WRITE) {
                addBytes(Byte.valueOf((byte) (this.mByteValue.length & 255)));
            }
            ByteUtils.writeFixedLengthString(this, this.mKey.getString(), this.mKey.getString().length());
            if (this.mCommand == RegistryCommand.WRITE) {
                addBytes(this.mByteValue);
            }
        }
        return super.getBytes();
    }
}
